<template>
  <div class="task_form_dialog">
    <!-- 机构编辑弹框 -->
    <el-dialog
      v-model="visible"
      :title="`${isEdit ? '编辑' : '新建'}机构`"
      :append-to-body="true"
      :show-close="false"
      :close-on-click-modal="false"
      top="20vh"
      center
      width="680px"
    >
      <div v-loading="dialogLoading" class="dialog_container">
        <div class="form_box f_1">
          <el-form
            ref="formRef"
            :rules="rules"
            :model="form"
            label-width="125px"
            size="small"
          >
            <el-form-item label="机构名称：" prop="orgName">
              <el-input
                v-model.trim="form.orgName"
                maxlength="50"
                placeholder="请输入机构名称"
              ></el-input>
            </el-form-item>

            <el-form-item label="机构简称：" prop="orgShortName">
              <el-input
                v-model.trim="form.orgShortName"
                maxlength="10"
                placeholder="请输入机构简称"
              ></el-input>
            </el-form-item>

            <el-form-item label="机构描述：" prop="orgDesc">
              <el-input
                v-model="form.orgDesc"
                type="textarea"
                rows="4"
                placeholder="请输入机构描述"
              ></el-input>
            </el-form-item>

            <el-form-item
              v-if="managerVisibel"
              label="机构管理员："
              prop="orgManagerName"
            >
              <el-input
                v-model="form.orgManagerName"
                placeholder="请选择机构管理员"
                maxlength="50"
                disabled
              ></el-input>
            </el-form-item>

            <el-form-item
              v-if="canJoinVisibel"
              label="是否可加入："
              prop="canJoin"
            >
              <el-radio-group v-model="form.canJoin">
                <el-radio
                  v-for="(item, i) in prepareData.canJoinSelectList"
                  :key="i"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="是否开启验证：" prop="isOpenVerification">
              <el-radio-group
                v-model="form.isOpenVerification"
                @change="changeIsOpenVerification"
                :disabled="form.canJoin !== '1'"
              >
                <el-radio
                  v-for="(item, i) in prepareData.isOpenVerificationSelectList"
                  :key="i"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="验证的问题：" prop="verifyQuestion">
              <el-input
                v-model.trim="form.verifyQuestion"
                placeholder="请输入验证的问题"
                maxlength="50"
                :disabled="
                  form.isOpenVerification !== '1' || form.canJoin !== '1'
                "
              ></el-input>
            </el-form-item>

            <el-form-item label="验证的答案：" prop="verifyAnswer">
              <el-input
                v-model.trim="form.verifyAnswer"
                placeholder="请输入验证的答案"
                maxlength="50"
                :disabled="
                  form.isOpenVerification !== '1' || form.canJoin !== '1'
                "
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog_footer">
          <el-button
            type="primary"
            @click="handleConfirm"
            :loading="confirmBtnLoading"
            size="small"
          >
            保存
          </el-button>
          <el-button @click="close" size="small">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const initFormData = () => {
  return {
    id: null,
    orgName: null,
    orgShortName: null,
    orgDesc: null,
    // 机构管理员id
    orgManagerId: null,
    // 机构管理员名称
    orgManagerName: null,
    // 是否可加入: 1 是，2 否
    canJoin: "1",
    isOpenVerification: "0",
    verifyQuestion: null,
    verifyAnswer: null,
  };
};

export default {
  name: "OrgFormDialog",
  props: {
    // 预加载数据
    prepareData: {
      type: Object,
      default: () => {
        return {
          canJoinSelectList: [],
        };
      },
    },
    // 【是否可加入】是否可见，默认隐藏
    canJoinVisibel: {
      type: Boolean,
      default: false,
    },
    // 【机构管理员】是否可见，默认可见
    managerVisibel: {
      type: Boolean,
      default: true,
    },
  },
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const router = useRouter();

    const isEdit = ref(false);
    // 弹框是否显示
    const visible = ref(false);
    // 是否开启整个弹框loading（开启时无法关闭弹框）
    const dialogLoading = ref(false);
    // 确认按钮loading（开启时可以关闭弹框）
    const confirmBtnLoading = ref(false);
    // 表单的引用
    const formRef = ref(null);
    // 表单数据
    const form = reactive(initFormData());
    // 表单校验规则
    const rules = reactive({
      orgName: [{ required: true, message: "请输入机构名称", trigger: "blur" }],
      orgShortName: [
        { required: true, message: "请输入机构简称", trigger: "blur" },
      ],
      canJoin: [
        { required: true, message: "请选择是否可加入", trigger: "blur" },
      ],
      isOpenVerification: [
        { required: true, message: "请选择是否开启验证", trigger: "blur" },
      ],
      verifyQuestion: [
        {
          required: true,
          trigger: "blur",
          validator: (rule, value, callback) => {
            if (!value && form.isOpenVerification === "1") {
              callback(new Error("请输入验证的问题"));
            } else {
              callback();
            }
          },
        },
      ],
      verifyAnswer: [
        {
          required: true,
          trigger: "blur",
          validator: (rule, value, callback) => {
            if (!value && form.isOpenVerification === "1") {
              callback(new Error("请输入验证的答案"));
            } else {
              callback();
            }
          },
        },
      ],
    });

    const handleConfirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          saveOrUpdate();
        } else {
          return false;
        }
      });
    };

    // 保存/修改接口
    const saveOrUpdate = () => {
      confirmBtnLoading.value = true;
      $api.organization
        .saveOrUpdate(form)
        .then((res) => {
          confirmBtnLoading.value = false;
          ElMessage.success(`${isEdit.value ? "修改" : "创建"}成功！`);
          // 触发事件，把数据传递给父组件
          context.emit("updateSuccess", res.data.id, form.verifyAnswer);
          close();
        })
        .catch((err) => {
          confirmBtnLoading.value = false;
          console.error("updateByAdmin error: ", err);
        });
    };

    const changeIsOpenVerification = () => {
      // if (form.isOpenVerification !== "1") {
      //   form.verifyQuestion = null;
      //   form.verifyAnswer = null;
      // }
    };

    // 打开弹框
    const open = (row) => {
      if (row) {
        Object.keys(form).forEach((item) => {
          form[item] = row[item];
        });
        isEdit.value = true;
      } else {
        isEdit.value = false;
      }
      visible.value = true;
    };

    // 关闭弹框
    const close = () => {
      if (confirmBtnLoading.value || dialogLoading.value) {
        return;
      }
      resetData();
      visible.value = false;
    };

    // 重置数据
    const resetData = () => {
      // 重置表单校验
      formRef.value && formRef.value.resetFields();
      // 重置表单数据
      Object.keys(form).forEach((item) => {
        form[item] = initFormData()[item];
      });
    };

    return {
      visible,
      dialogLoading,
      confirmBtnLoading,
      formRef,
      form,
      rules,
      open,
      close,
      handleConfirm,
      isEdit,
      changeIsOpenVerification,
    };
  },
};
</script>
